import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getInfo as getInfoApi, login as loginApi, logout as logoutAPI } from '../api/user'
import { getToken, removeToken, setToken, setTokenB } from '../utils/auth'
import { webSocketService } from '../utils/websocket'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const tokenB = ref('')
  // 首次加载先从 cookie 获取 token
  token.value = getToken() || ''

  /**
   * @description: 登录
   * @param {*} userInfo 用户名/密码
   * @return {*}
   */
  async function login(userInfo: { username: string; password: string }) {
    const { username, password } = userInfo
    const { data } = await loginApi({ username: username.trim(), password })
    const tokenStr = data.tokenHead + data.token
    // 存储 token 到 cookie 中
    setToken(tokenStr)
    setTokenB(data.token)
    token.value = tokenStr
    tokenB.value = data.token
    // 登录成功后建立WebSocket连接
    setTimeout(() => {
      webSocketService.connect()
    }, 1000) // 延迟1秒确保用户信息已获取
  }

  // 用户名
  const name = ref('')
  // 用户id
  const userId = ref()
  // 角色身份
  const roles = ref<string[]>([])
  // 有权限的菜单和按钮
  const permissionIds = ref<string[]>([])

  /**
   * @description: 获取用户信息
   * @return {*}
   */
  async function getInfo() {
    const { data } = await getInfoApi(token.value)
    if (!data) return {}

    roles.value = data.roles || []
    userId.value = data.id
    name.value = data.username
    data.Permissions.forEach((item: any) => {
      permissionIds.value.push(item.permCode)
    })

    // 如果有token但WebSocket未连接，则尝试连接
    if (tokenB.value && !webSocketService.getConnectionStatus()) {
      webSocketService.connect()
    }

    return data
  }

  /**
   * @description: 退出登录
   * @return {*}
   */
  async function logout() {
    await logoutAPI()
    removeToken()
    resetState()

    // 手动断开WebSocket连接，并禁用自动重连
    webSocketService.disconnect(true)
  }

  function resetState() {
    token.value = ''
    name.value = ''
    roles.value = []
  }

  return {
    userId,
    login,
    token,
    name,
    getInfo,
    roles,
    logout,
    permissionIds,
    tokenB
  }
})
